//
//  MMGRefreshControl.swift
//  MyMicroblog
//
//  Created by Mac on 17/1/10.
//  Copyright © 2017年 itcast. All rights reserved.
//

import UIKit

// 为刷新控件的三种状态提供枚举值
enum RefreshStatue: Int {
    case Normal = 0          // 默认状态
    case Already = 1         // 准备加载
    case Freshing = 2        // 正在刷新
}
private let freshHeight: CGFloat = 60
class MMGRefreshControl: UIControl {
    
    // 设置状态
    private var statue:RefreshStatue = .Normal {
        didSet{
            switch statue {
            case .Normal:   // 默认状态
                tipLabel.text = "下拉刷新"
                indicator.stopAnimating()
                arrowImage.isHidden = false
                // 箭头方向为向下正向
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowImage.transform = CGAffineTransform.identity
                })
                // 判断上个值的状态
                if oldValue == .Freshing {
                    // 隐藏控件
                    UIView.animate(withDuration: 0.25, animations: { 
                        self.scrollView?.contentInset.top = self.scrollView!.contentInset.top - freshHeight
                    })
                }
            case .Already:
                 tipLabel.text = "松手刷新"
                // 修改箭头方向为向上,旋转180度
                UIView.animate(withDuration: 0.25, animations: { 
                    self.arrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(M_PI))
                })
            case .Freshing:
                tipLabel.text = "正在刷新"
                indicator.startAnimating()
                arrowImage.isHidden = true
                // 发送值改变消息
                sendActions(for: .valueChanged)
                // 修改父视图内偏距,显示控件
                UIView.animate(withDuration: 0.25, animations: { 
                    self.scrollView?.contentInset.top = self.scrollView!.contentInset.top + freshHeight
                })
            }
        }
    }
    
    // 为父控件设置观察者为刷新控件本身,使用 KVO,在控件加入到父控件上时添加
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        if let fatherView = newSuperview as? UIScrollView {
            self.scrollView = fatherView
            self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
        }
    }
    
    // 停止刷新
    func endFreshing() {
        statue = .Normal
    }
    
    // 实现观察者监听方法
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        // 根据观察消息,判断父控件中刷新控件的状态
        // 计算偏移量
        let offsetY = scrollView?.contentOffset.y ?? 0
        let targetY = -(navBarHeight + freshHeight)
        // 正在被拖拽
        if scrollView!.isDragging {
            if statue == .Normal && offsetY < targetY {
                statue = .Already
            }else if statue == .Already && offsetY > targetY {
                statue = .Normal
            }
        }else{
        // 拖拽结束,开始刷新
            if statue == .Already {
                statue = .Freshing
            }
        }
    }
    
    // 设置 UI 界面信息
    private func setupUI() {
        // 将控件加载到根视图中
        addSubview(backgroundView)
        addSubview(tipLabel)
        addSubview(arrowImage)
        addSubview(indicator)
        
        // 设置约束
        backgroundView.snp.makeConstraints { (make) in
            make.left.right.bottom.equalTo(self)
        }
        tipLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        arrowImage.snp.makeConstraints { (make) in
            make.centerY.equalTo(tipLabel)
            make.right.equalTo(tipLabel.snp.left)
        }
        indicator.snp.makeConstraints { (make) in
            make.center.equalTo(arrowImage)
        }
    }
    
    // 重写构造方法,设置固定尺寸的控件
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: navBarHeight - freshHeight, width: ScreenWidth, height: freshHeight))
        self.backgroundColor = UIColor.blue
        setupUI()
    }
    
    // 禁止使用 xib 或者 sb 创建对象
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 懒加载父控件
    var scrollView: UIScrollView?
    // 懒加载控件
    // 懒加载提示文字框
    lazy var tipLabel: UILabel = UILabel(text: "下拉起飞", textColor: UIColor.orange, textFontSize: 14)
    // 懒加载箭头图片
    lazy var arrowImage: UIImageView = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    // 懒加载刷新指示器
    lazy var indicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white)
    // 懒加载背景图
    lazy var backgroundView: UIImageView = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    // 移除观察者
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contentOffset", context: nil)
    }
}
